package com.gzhuxj201.controller;

import com.gzhuxj201.entity.Result;
import com.gzhuxj201.entity.StuFile;
import com.gzhuxj201.entity.Student;
import com.gzhuxj201.util.ZipUtils;
import com.gzhuxj201.mapper.StuFileMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipOutputStream;

@RestController
@Slf4j
public class FileController {
    @Autowired
    private StuFileMapper stuFileMapper;

        @PostMapping("/upload")
        public Result upload(MultipartFile file, HttpSession session) throws IOException {
            log.info("文件上传：{}",  file);
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //构建新的文件名
            String extname = originalFilename.substring(originalFilename.lastIndexOf("."));//文件扩展名
            String newFileName = UUID.randomUUID().toString()+extname;//随机名+文件扩展名
            //将文件存储在服务器的磁盘目录
            String realPath=ResourceUtils.getURL("classpath:").getPath()+"static/files";
            File filePath = new File(realPath);
            if(!filePath.exists()){
                filePath.mkdirs();
            }
            file.transferTo(new File(realPath,newFileName));

            Student student =(Student)session.getAttribute("user");
            StuFile reStuFile = new StuFile();
            reStuFile.setName(file.getOriginalFilename());
            reStuFile.setNewName(newFileName);
            reStuFile.setSno(student.getSno());
            reStuFile.setStudentName(student.getUsername());

            return Result.success(reStuFile);
        }



    @RequestMapping(path = "/deleteFile",method = RequestMethod.DELETE)
    public Result deleteFile(Integer homeWorkId,String sno) throws Exception {
        StuFile stuFile = stuFileMapper.selectByHomeWorkIdAndSno(homeWorkId, sno);
        //删除文件
        String newName = stuFile.getNewName();
        String realPath=ResourceUtils.getURL("classpath:").getPath()+"/static/files";
        File file = new File(realPath, newName);
        if(file.exists()){
            file.delete();
        }
        //删除数据库中的记录
        int res= stuFileMapper.deleteByHomeWorkAndSno(homeWorkId,sno);
        return Result.success();
    }

    @RequestMapping(path = "/download",method = RequestMethod.GET)
    public void download(String openStyle,Integer homeWorkId,String sno, HttpServletResponse response) throws Exception {

         StuFile stuFile= stuFileMapper.selectByHomeWorkIdAndSno(homeWorkId,sno);

        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files/";
        FileInputStream is=new FileInputStream(new File(realPath,stuFile.getNewName()));
        //设置响应头打开方式content-disposition,即为点击下载弹出选择 inline(在线打开)  attachment(附件下载)
        response.setHeader("content-disposition",openStyle+";filename="+URLEncoder.encode(stuFile.getName(),"utf-8"));
        //获取响应输出流
        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(is,os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

    @RequestMapping(path = "/downloads/{newNames}",method = RequestMethod.GET)
    public void downloads(@PathVariable List<String> newNames, HttpServletResponse response) throws Exception {
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files/";
        File resFiles = new File(realPath + "resFiles/");
        if(!resFiles.exists()){
            resFiles.mkdirs();
        }
        //log.info(newNames.toString());

        for (String newName : newNames) {
            String fileName=newName;
            FileInputStream is=new FileInputStream(new File(realPath,fileName));
            FileOutputStream os=new FileOutputStream(new File(resFiles,fileName));
            IOUtils.copy(is,os);
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
        //log.info("写入已执行");
        /*
         *   压缩流
         *      需求：
         *          把D:\\aaa文件夹压缩成一个压缩包
         * */
        //1.创建File对象表示要压缩的文件夹
        File src = resFiles;
        //2.创建File对象表示压缩包放在哪里（压缩包的父级路径）
        File destParent = src.getParentFile();//D:\\
        //3.创建File对象表示压缩包的路径
        File dest = new File(destParent,src.getName() + ".zip");
        //4.创建压缩流关联压缩包
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest));
        //5.获取src里面的每一个文件，变成ZipEntry对象，放入到压缩包当中
        ZipUtils.toZip(src,zos,src.getName());//aaa
        //6.释放资源
        zos.close();
        //log.info("已压缩成zip文件");


        FileInputStream is=new FileInputStream(new File(realPath,src.getName() + ".zip"));
        //设置响应头打开方式content-disposition,即为点击下载弹出选择 inline(在线打开)  attachment(附件下载)
        response.setHeader("content-disposition","attachment;filename="+URLEncoder.encode(src.getName() + ".zip","utf-8"));
        //获取响应输出流
        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(is,os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);

    }



}
